<template>
  <div class="page-container">
    <div class="common-content-wrap">
      <TrTable
        ref="trTable"
        isNeedSelection
        isNeedIndex
        :btnList="btnList"
        :total="totalNum"
        v-model="searchParams"
        :searchShowList="searchShowList"
        :searchHideList="searchHideList"
        :tableColumn="tableColumn"
        requestName="searchHandle"
        :tableData="tableData"
        @add="isShowEdit = true"
        @print="operateHandle($event, 'print')"
        @export="operateHandle($event, 'export')"
        @remove="operateHandle($event, 'remove')"
        @view="operateHandle($event, 'view')"
        @rowExport="operateHandle($event, 'rowExport')"
        @rowPrint="operateHandle($event, 'rowPrint')"
        @rowRemove="operateHandle($event, 'rowRemove')"
      />
    </div>
    <TrEditPopup
      ref="TrEditPopup"
      :width="1227"
      :labelWidth="114"
      v-model="isShowEdit"
      title="新增"
      :valueObj.sync="formObj"
      :formData="formData"
      :list="popupList"
      :footerList="footerList"
      @close="closeAddPopup"
      @confrim="editConfirmHandle"
      @printConfrim="printConfrim"
      @select-change="changeSelectHandle"
    >
      <template #addTable>
        <TrTable
          isPopup
          isNeedIndex
          :isNeedPagination="false"
          :tableData="addPopuptableData"
          :total="addPopuptotalNum"
          :tableColumn="addPopupTableColumn"
          requestName="getBomListHandle"
          @input-back="inputBlurHandle"
        />
      </template>
    </TrEditPopup>
    <TrDetail
      v-model="isShowDetailPopup"
      popupTitle="查看领料"
      :leftList="detailList"
      statusModel="hidden"
      :width="1227"
      :detailData="detailData"
      :isNeedFooter="false"
      @close="closeDetailPopup"
    >
      <template #bomTable>
        <TrTable
          isPopup
          isNeedIndex
          v-model="bomSearchParams"
          :isNeedPagination="false"
          :tableData="bomTableData"
          :tableColumn="bomTableColumn"
          requestName="getBomListHandle"
          @viewDeatil="getDetailTableHandle($event)"
        />
        <TrDetail
          v-model="isShowDetailInnerPopup"
          popupTitle="查看领料"
          :leftList="detailInnerList"
          statusModel="hidden"
          :width="1227"
          :isNeedFooter="false"
          :detailData="detailInnerData"
          @close="closeDetailInnerPopup"
        >
          <template #bomTable>
            <TrTable
              isPopup
              isNeedIndex
              :isNeedPagination="false"
              :tableData="bomInnerTableData"
              :total="bomInnerTotal"
              :tableColumn="bomInnerTableColumn"
              requestName="getBomListHandle"
            />
          </template>
        </TrDetail>
      </template>
    </TrDetail>
    <div class="print-wrap">
      <ProductionMaterialPrint ref="printRef" :printList="printList" />
    </div>
  </div>
</template>

<script>
import {
  getList,
  getEnum,
  getDetail,
  getDetailTable,
  save,
  remove,
  getPrintData,
  getAddWorkOrderTable,
} from "@/api/logistics/productionMaterialRequisition";
import { getStore } from "@/utils/store";
import { getColor } from "@/utils/billColor";
import ProductionMaterialPrint from "./components/ProductionMaterialPrint.vue";
import TrTable from "@/components/Tr-table/Tr-table.vue";
import TrEditPopup from "@/components/Tr-edit/Tr-edit-popup.vue";
import TrDetail from "@/components/Tr-detail/Tr-detail.vue";

export default {
  components: {
    TrTable,
    TrEditPopup,
    TrDetail,
    ProductionMaterialPrint,
  },
  data: () => ({
    tableColumn: [
      {
        type: "text",
        label: "领料单号",
        value: "relationBillCode",
      },
      {
        type: "text",
        label: "工单单号",
        value: "workOrderCode",
      },
      {
        type: "text",
        label: "领料数量",
        value: "materialNum",
      },
      {
        type: "text",
        label: "数量单位",
        value: "newNumUnit",
      },
      {
        type: "text",
        label: "领料重量",
        value: "materialWeight",
      },
      {
        type: "text",
        label: "重量单位",
        value: "newWeightUnit",
      },
      {
        type: "text",
        label: "单据状态",
        value: "stateName",
      },
      {
        type: "text",
        label: "创建人员",
        value: "createUserName",
      },
      {
        type: "text",
        label: "创建时间",
        value: "createTime",
      },
      {
        type: "option",
        label: "操作",
        fixed: "right",
        width: 120,
        showBtnList: [
          {
            label: "查看",
            option: "view",
          },
        ],
        hideBtnList: [
          // {
          //   label: "导出",
          //   option: "rowExport",
          // },
          {
            label: "打印",
            option: "rowPrint",
          },
          {
            label: "删除",
            option: "rowRemove",
          },
        ],
      },
    ],
    searchHideList: [
      {
        id: "relationBillCode",
        type: "input",
        width: 33.33,
        label: "领料单号",
        value: "",
      },
      {
        id: "workOrderId",
        type: "loadselect",
        width: 33.33,
        label: "工单单号",
        value: "",
        requestObj: {
          url: "/api/mes-production-service/work-order/page",
          method: "post",
          searchKey: "workOrderCode",
          rlLabel: "workOrderCode",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        id: "stateList",
        type: "multiSelect",
        width: 33.33,
        label: "状态",
        list: [],
        value: [],
      },
      // {
      //   id: "purcOrderCode",
      //   type: "input",
      //   width: 33.33,
      //   label: "领用类型",
      //   value: "",
      // },
    ],
    searchShowList: [
      {
        isNeed: true,
        startStr: "createTimeStart",
        endStr: "createTimeEnd",
        id: "createdTime",
        type: "daterange",
        width: 80,
        label: "创建时间",
        value: [],
        timePeriod: true,
        radio: 1,
      },
    ],
    btnList: [
      {
        label: "新增",
        option: "add",
        color: "blue",
      },
      {
        label: "打印",
        option: "print",
        color: "white",
        isRelaTable: true,
      },
      {
        label: "导出",
        option: "export",
        color: "white",
      },
      {
        label: "删除",
        option: "remove",
        color: "white",
        isRelaTable: true,
      },
    ],
    tableData: [],
    printList: [],
    searchParams: {
      current: 1,
      size: 10,
    },
    totalNum: 0,
    // 新增编辑弹窗
    formObj: {},
    formData: {},
    popupList: [
      {
        label: "工单单号",
        type: "loadselect",
        width: 33.3,
        value: "",
        list: [],
        id: "workOrderId",
        selectedLabel: "",
        reviewLabel: "categoryName",
        requestObj: {
          url: "/api/mes-production-service/work-order/page",
          method: "post",
          searchKey: "workOrderCode",
          rlLabel: "workOrderCode",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        defaultParams: {
          stateList: [20, 10],
        },
      },
      {
        label: "工单计划数量",
        type: "input",
        width: 33.3,
        value: "",
        disabled: true,
        id: "stationName",
      },
      {
        label: "领料车间",
        type: "loadselect",
        width: 33.3,
        value: "",
        list: [],
        id: "destProdOrgId",
        selectedLabel: "",
        reviewLabel: "categoryName",
        requestObj: {
          url: "/api/trio-system/prod-org/page",
          method: "post",
          searchKey: "orgName",
          rlLabel: "orgName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        defaultParams: {
          orgLevelCode: "WORKSHOP",
          parentId: getStore({ name: "factoryId" }),
        },
      },
      {
        type: "slot",
        slotName: "addTable",
        width: 100,
        isNeed: false,
      },
    ],
    addPopupTableColumn: [
      {
        type: "text",
        label: "原料料号",
        value: "materialCode",
      },
      {
        type: "text",
        label: "物料名称",
        value: "materialName",
      },
      {
        type: "text",
        label: "物料规格",
        value: "materialSpec",
      },
      {
        type: "text",
        label: "仓库名称",
        value: "sourceWarehouseName",
      },
      {
        type: "text",
        label: "可领数量",
        value: "canPickNum",
      },
      {
        type: "text",
        label: "数量单位",
        value: "newNumUnit",
      },
      {
        type: "text",
        label: "可领重量",
        value: "canPickWeight",
      },
      {
        type: "text",
        label: "重量单位",
        value: "newWeightUnit",
      },
      {
        type: "input",
        label: "领用数量",
        value: "num",
        inputType: "number",
      },
      {
        type: "text",
        label: "数量单位",
        value: "newNumUnit",
      },
      {
        type: "input",
        label: "领用重量",
        value: "weight",
        inputType: "number",
        disabled: true,
        placeholder: "系统带出",
      },
      {
        type: "text",
        label: "重量单位",
        value: "newWeightUnit",
      },
      {
        type: "input",
        label: "备注",
        value: "remark",
        inputType: "text",
      },
    ],
    addPopuptableData: [],
    addPopuptotalNum: 0,
    footerList: [
      {
        label: "取消",
        option: "close",
        color: "white",
      },
      {
        label: "保存打印",
        option: "printConfrim",
        color: "white",
      },
      {
        label: "保存",
        option: "confrim",
        color: "blue",
      },
    ],
    isShowEdit: false,
    detailData: {},
    isShowDetailPopup: false,
    detailList: [
      {
        type: "text",
        label: "基础信息",
        list: [
          {
            width: 33.3,
            text: "领料单号",
            id: "relationBillCode",
          },
          {
            width: 33.3,
            text: "工单单号",
            id: "workOrderCode",
          },
          {
            width: 33.3,
            text: "领料车间",
            id: "destProdOrgName",
          },
          {
            width: 33.3,
            text: "创建人",
            id: "createUserName",
          },
          {
            width: 33.3,
            text: "创建时间",
            id: "createTime",
          },
          {
            width: 33.3,
            text: "工单状态",
            id: "stateName",
          },
        ],
      },
      {
        type: "slot",
        slotName: "bomTable",
        label: "操作信息",
        slotBottom: 32,
      },
    ],
    bomSearchParams: {
      current: 1,
      size: 10,
    },
    bomTotal: 0,
    bomTableColumn: [
      {
        type: "text",
        label: "原料料号",
        value: "materialCode",
      },
      {
        type: "text",
        label: "物料名称",
        value: "materialName",
      },
      {
        type: "text",
        label: "物料规格",
        value: "materialSpec",
      },
      {
        type: "text",
        label: "仓库名称",
        value: "warehouseName",
      },
      {
        type: "text",
        label: "领用数量",
        value: "num",
      },
      {
        type: "text",
        label: "数量单位",
        value: "newNumUnit",
      },
      {
        type: "text",
        label: "领用重量",
        value: "weight",
      },
      {
        type: "text",
        label: "重量单位",
        value: "newWeightUnit",
      },
      {
        type: "text",
        label: "备注",
        value: "remark",
      },
      {
        type: "option",
        label: "操作",
        fixed: "right",
        width: 80,
        showBtnList: [
          {
            label: "查看",
            option: "viewDeatil",
          },
        ],
      },
    ],
    bomTableData: [],
    detailInnerData: {},
    isShowDetailInnerPopup: false,
    detailInnerList: [
      {
        type: "text",
        label: "备料信息",
        list: [
          {
            width: 33.33,
            text: "原料料号",
            id: "materialCode",
          },
          {
            width: 33.33,
            text: "物料名称",
            id: "materialName",
          },
          {
            width: 33.33,
            text: "物料规格",
            id: "materialSpec",
          },
          {
            width: 33.33,
            text: "仓库名称",
            id: "sourceWarehouseName",
          },
          {
            width: 33.33,
            text: "领用数量",
            id: "num",
          },
          {
            width: 33.33,
            text: "数量单位",
            id: "newNumUnit",
          },
          {
            width: 33.33,
            text: "领用重量",
            id: "weight",
          },
          {
            width: 33.33,
            text: "重量单位",
            id: "newWeightUnit",
          },
          {
            width: 33.33,
            text: "备料人员",
            id: "readyUserName",
          },
          {
            width: 33.33,
            text: "备料时间",
            id: "readyTime",
          },
        ],
      },
      {
        type: "slot",
        slotName: "bomTable",
        label: "操作信息",
        slotBottom: 32,
      },
    ],
    bomInnerTotal: 0,
    bomInnerTableColumn: [
      {
        type: "text",
        label: "物料标签",
        value: "barcode",
      },
      {
        type: "text",
        label: "物料数量",
        value: "num",
      },
      {
        type: "text",
        label: "数量单位",
        value: "newNumUnit",
      },
      {
        type: "text",
        label: "物料重量",
        value: "weight",
      },
      {
        type: "text",
        label: "重量单位",
        value: "newWeightUnit",
      },
    ],
    bomInnerTableData: [],
  }),
  computed: {
    checkTitle() {
      const titles = {
        add: "新增",
        default: "编辑",
      };
      return titles[this.currentHandle] || titles.default;
    },
    ids() {
      let ids = [];
      this.$refs.trTable.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    },
  },
  mounted() {
    this.getEnmuData();
    // this.getListHandle();
    // const userInfo = getStore({ name: "factoryId" });
    // console.log(userInfo, "==================");
  },
  methods: {
    inputBlurHandle(item, val, index) {
      console.log(item, val, index, "ppppppp");
      if (item.value != "num") return;
      if (val.num != Math.floor(val.num)) {
        this.$set(this.addPopuptableData[index], "num", "");
        return this.$message.warning("领用数量请输入整数");
      }
      if (val.num > val.canPickNum) {
        this.$set(this.addPopuptableData[index], "num", "");
        return this.$message.warning("领用数量不能超过可领数量");
      }
      let computedWeight = Number(val.num * val.standardWeight).toFixed(6);
      this.$set(this.addPopuptableData[index], "weight", computedWeight);
      console.log(123456, this.addPopupTableColumn);
    },
    getEnmuData() {
      getEnum(["PickBizBillStateEnum"]).then((res) => {
        if (res.data.code != 200) return;
        let state = this.$findByProperty(
          this.searchHideList,
          "id",
          "stateList"
        );
        console.log(res.data);
        this.$set(state, "list", res.data.data[0].list);
      });
    },
    async operateHandle(val, type) {
      this.currentHandle = type;

      this.$validateData(val, 3);

      const actions = {
        print: () => this.printHandle(this.ids),
        export: () =>
          this.$exportHandle({ vm: this, params: this.searchParams }),
        remove: () => this.removeHandle(this.ids),
        view: () => this.getDetailHandle(val),
        rowExport: () => this.exportHandle(),
        rowPrint: () => this.printHandle([val.id]),
        rowRemove: () => this.removeHandle([val.id]),
      };

      const action = actions[type];
      if (action) action();
    },
    editConfirmHandle() {
      let tempList = this.addPopuptableData.filter(
        (item) =>
          item.num &&
          item.num != 0 &&
          item.num !== "" &&
          item.num !== "-" &&
          item.weight &&
          item.weight !== "" &&
          item.weight !== "-"
      );
      if (tempList.length == 0)
        return this.$message.warning("请填写领用数量！");
      let params = {
        ...this.formObj,
        pickBizDetailSaveCMDList: tempList,
      };
      this.addHandle(params);
    },
    async printConfrim() {
      let params = {
        ...this.formObj,
        pickBizDetailSaveCMDList: this.addPopuptableData.filter(
          (item) =>
            item.num &&
            item.num != 0 &&
            item.num !== "" &&
            item.num !== "-" &&
            item.weight &&
            item.weight !== "" &&
            item.weight !== "-"
        ),
      };
      let bizBillId = await this.addHandle(params);
      this.printHandle([bizBillId]);
    },
    // exportHandle() {
    //   this.$textShow({
    //     title: "导出",
    //     content: [this.$t("tip.export")],
    //   })
    //     .then(() => {
    //       this.$load.show();
    //       this.searchParams.size = 1000;
    //       exportData(this.searchParams)
    //         .then((res) => {
    //           if (res.status != 200)
    //             return this.$message.error(this.$t("msg.exportFailed"));
    //           let timeStr = moment().format("YYYYMMDD-HHmmss");
    //           const fileName = `采购订单-${timeStr}` + ".xlsx";
    //           comExport(res.data, fileName);
    //           this.$message.success(this.$t("msg.exportSuccess"));
    //         })
    //         .finally(() => {
    //           this.searchParams.size = 10;
    //           this.$load.close();
    //         });
    //     })
    //     .catch(() => {});
    // },
    async removeHandle(ids) {
      await this.$textShow({
        title: "删除",
        content: [this.$t("tip.delete")],
      });
      const { data } = await remove({ ids });
      if (data.code !== 200) return;
      this.$message.success(this.$t("msg.success"));
      this.searchParams.current = 1;
      this.$refs.trTable.clearSelect();
      this.getListHandle();
    },
    async printHandle(ids) {
      this.printList = [];
      ids.forEach((item) => {
        getPrintData({
          bizBillId: item,
          current: 1,
          size: 30,
        }).then((res) => {
          if (res.data.code !== 200) return;

          this.$validateData(res.data.data);
          this.printList.push(res.data.data);
        });
      });
      console.log(this.printList);
      await this.$textShow({
        title: "打印",
        content: [this.$t("tip.print")],
      });
      this.$refs.printRef.printHandle();
      this.$refs.trTable.clearSelect();
    },
    async addHandle(params) {
      params.pickBizDetailSaveCMDList.forEach((item) => {
        item.numUnitCode = item.invNumU9UnitCode;
        item.weightUnitCode = item.invWeightU9UnitCode;
      });
      let res = await save(params);

      if (res.status != 200) return;
      this.$message.success(this.$t("msg.success"));
      await this.getListHandle();
      this.isShowEdit = false;
      this.addPopuptableData = [];
      console.log(res);
      return res.data.data.bizBillId;
    },
    changeSelectHandle(val) {
      console.log(val);
      if (val.ftId == "workOrderId") {
        this.getAddTableData(val.workOrderCode);
      }
    },
    async getDetailHandle(val) {
      const { data } = await getDetail({
        bizBillId: val.id,
        current: 1,
        size: 30,
      });
      if (data.code !== 200) return;

      this.$validateData(data.data);
      console.log(data);
      this.detailData = {
        ...data.data,
        stateName: val.stateName,
        createUserName: val.createUserName,
        createTime: val.createTime,
      };
      const col = this.$findByProperty(
        this.detailList,
        "id",
        "stateName",
        "list"
      );
      col.valueColor = getColor("LLD", data.data.state);
      this.bomTableData = data.data.bizDetailDetailList;
      this.bomTableData.forEach((item) => {
        item.newNumUnit = `${item.numUnitCode}(${item.numUnitName})`;
        item.newWeightUnit = `${item.weightUnitCode}(${item.weightUnitName})`;
      });
      this.isShowDetailPopup = true;
    },
    getAddTableData(workOrderCode) {
      const cloneList = this.$refs.TrEditPopup?.$refs.trEdit?.cloneList;
      let planNum = this.$findByProperty(cloneList, "id", "stationName");
      getAddWorkOrderTable({
        workOrderCode,
        current: 1,
        size: 30,
      })
        .then(({ data }) => {
          console.log(data);
          if (data.code !== 200) {
            this.addPopuptableData = [];
            this.$set(planNum, "value", "");
            return;
          }
          // this.$validateData(data.data);

          this.$set(planNum, "value", data.data.planNum);
          this.addPopuptableData = data.data.pickInvTransRespList;
          this.addPopuptableData.forEach((item) => {
            item.newNumUnit = `${item.numUnitCode}(${item.numUnitName})`;
            item.newWeightUnit = `${item.weightUnitCode}(${item.weightUnitName})`;
          });
        })
        .catch(() => {
          this.addPopuptableData = [];
          this.$set(planNum, "value", "");
        });
    },
    async getDetailTableHandle(val) {
      console.log(val);
      const { data } = await getDetailTable({
        bizDetailId: val.bizDetailId,
        current: 1,
        size: 30,
      });

      if (data.code !== 200) return;
      this.$validateData(data.data);
      this.isShowDetailInnerPopup = true;
      this.detailInnerData = {
        ...data.data,
        newNumUnit: `${data.data.numUnitCode}(${data.data.numUnitName})`,
        newWeightUnit: `${data.data.weightUnitCode}(${data.data.weightUnitName})`,
      };
      this.bomInnerTableData = data.data.billBarcodePageList.records;
      this.bomInnerTableData.forEach((item) => {
        item.newNumUnit = `${item.numUnitCode}(${item.numUnitName})`;
        item.newWeightUnit = `${item.weightUnitCode}(${item.weightUnitName})`;
      });
      this.bomTotal = Number(data.data.total);
    },
    closeAddPopup() {
      this.isShowEdit = false;
      this.addPopuptableData = [];
    },
    closeDetailPopup() {
      this.isShowDetailPopup = false;
    },
    closeDetailInnerPopup() {
      this.isShowDetailInnerPopup = false;
    },
    searchHandle() {
      this.getListHandle();
    },
    async getListHandle() {
      const { data } = await getList(this.searchParams);
      console.log(data);
      if (data.code != 200) return;

      this.$validateData(data.data);
      this.tableData = data.data.records;
      this.totalNum = Number(data.data.total);
      this.tableData.forEach((item) => {
        item["stateNameColor"] = getColor("LLD", item.state);
        item.newNumUnit = `${item.materialNumUnit}(${item.materialNumUnitName})`;
        item.newWeightUnit = `${item.materialWeightUnit}(${item.materialWeightUnitName})`;
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.print-wrap {
  position: fixed;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: -999;
  opacity: 0;
}
</style>
